package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Menu;
import com.qf.service.MenuService;
import com.qf.utils.MenuExcleUtil;
import com.qf.utils.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 2019/12/11
 * 郭程鹏
 * springboot_oa_five
 * 面向代码面向君,不负时光不负卿
 */
@Controller
public class MenuController {

    @Autowired
    private MenuService menuService;
    //异步校验权限码
    @RequestMapping("/resource/system/menu/ajaxPreCode")
    @ResponseBody
    public Integer ajaxPreCode(@RequestParam("preCode") String preCode){
        Integer ajaxPreCode = menuService.ajaxPreCode(preCode);

        return ajaxPreCode;
    }

    //异步校验URL是否可用
    @RequestMapping("/resource/system/menu/ajaxUrl")
    @ResponseBody
    public Integer ajaxUrl(@RequestParam("menuUrl") String menuUrl){
        Integer ajaxUrl = menuService.ajaxUrl(menuUrl);
        return  ajaxUrl;
    }

    //菜单模糊分页
    @RequestMapping("/resource/system/menu/list")
    public String menuList(Model model, @RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "") String menuName){
        PageInfo<Menu> menu = menuService.findAllMenu(page,menuName);
        model.addAttribute("pageInfo",menu);
        model.addAttribute("menuName",menuName);

        return "resource/system/menu/list";
    }


    //添加菜单预览
    @RequestMapping("/resource/system/menu/preAdd")
    public String preAdd(Model model){

        List<Menu> fatherMenu = menuService.findFatherMenu();
        model.addAttribute("menu",fatherMenu);

        return "resource/system/menu/add";
    }
    //异步校验用户名
    @RequestMapping("/resource/system/menu/ajaxName")
    @ResponseBody
    public Integer ajaxMenuName(String menuName){

        Integer ajaxMenuName = menuService.ajaxMenuName(menuName);
        return ajaxMenuName;

    }

    //添加菜单
    @RequestMapping("/resource/system/menu/addMenu")
    public void addMenu(Menu menu, HttpServletResponse re){
        try {
            re.setCharacterEncoding("utf-8");
            re.setContentType("text/html;charset=utf-8");
            Integer addMenu = menuService.addMenu(menu);
            if (addMenu>0){
                re.getWriter().print("<script>alert('菜单添加成功!');window.history.back();</script>");
            }else{
                re.getWriter().print("<script>alert('菜单添加失败!');window.history.back();</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                re.getWriter().print("<script>alert('系统繁忙请稍后再试!');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    //修改菜单回显
    @RequestMapping("/resource/system/menu/preEdit")
    public String preMenuEdit(Model model,@RequestParam("menuId") Integer menuId){
        List<Menu> fatherMenu = menuService.findFatherMenu();
        Menu myMenuById = menuService.findMyMenuById(menuId);
        model.addAttribute("menu",fatherMenu);
        model.addAttribute("oldMenu",myMenuById);
        return "resource/system/menu/edit";
    }
    //修改菜单
    @RequestMapping("/resource/system/menu/edit")
    public void editMenu(HttpServletResponse response,Menu menu){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
            menuService.updateMenu(menu);
            response.getWriter().print("<script>alert('菜单修改成功!');window.history.back();</script>");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("<script>alert('菜单修改出错!');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    //删除菜单
    @RequestMapping("/resource/system/menu/delete")
    public String deleteMenu(HttpServletResponse response,@RequestParam("menuId") Integer menuId,Model model, @RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "") String menuName){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
             List<Integer> list = menuService.checkMenuInMiddle(menuId);
            if (list.size()>0){
                response.getWriter().print("<script>alert('菜单正在使用中不可删除!');window.history.back();</script>");
            }else {
                menuService.deleteMenuIdInMiddleFromMiddel(menuId);
                response.getWriter().print("<script>alert('菜单删除成功!');</script>");
                PageInfo<Menu> menu = menuService.findAllMenu(page,menuName);
                model.addAttribute("pageInfo",menu);
                model.addAttribute("menuName",menuName);
                return "resource/system/menu/list";
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("<script>alert('删除菜单失败!系统繁忙请稍后重试!');window.history.back();</script>");

            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
            return null;
    }

    //禁用
    @RequestMapping("/resource/system/menu/status")
    public String nenuBan(HttpServletResponse response,@RequestParam("menuId") Integer menuId,Model model, @RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "") String menuName){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            menuService.menuBan(menuId);
            response.getWriter().print("<script>alert('菜单已禁用!');</script>");
            PageInfo<Menu> menu = menuService.findAllMenu(page,menuName);
            model.addAttribute("pageInfo",menu);
            model.addAttribute("menuName",menuName);
            return "resource/system/menu/list";

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("<script>alert('菜单禁用失败!系统繁忙，请稍后重试!');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
        return null;

    }

    //启用
    @RequestMapping("/resource/system/menu/active")
    public String nenuActive(HttpServletResponse response,@RequestParam("menuId") Integer menuId,Model model, @RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "") String menuName){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
            menuService.menuActive(menuId);
            response.getWriter().print("<script>alert('菜单已启用!');</script>");
            PageInfo<Menu> menu = menuService.findAllMenu(page,menuName);
            model.addAttribute("pageInfo",menu);
            model.addAttribute("menuName",menuName);
            return "resource/system/menu/list";

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("<script>alert('菜单启用失败!系统繁忙，请稍后重试!');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }


        }
       return null;
    }


    //批量导出
    @RequestMapping("/resource/system/menu/excleAndDeleteAll")
    public String ecxleAndDeleteAll(@RequestParam("menuId")List<Integer> menuId, @RequestParam("method") String method, HttpServletResponse response,Model model, @RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "") String menuName){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream outputStream=null;


        if (method.equals("doExcle")){
            try {
                List<Menu> menus = menuService.doExcle(menuId);
                outputStream=response.getOutputStream();
                //生成随机名字
                String number = NumberUtil.getNumber(6);
                //设置导出格式
                response.setContentType("application/x-download");
                String excleName = "excle_"+number+ ".xls";
                response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
                //excle表名
                MenuExcleUtil.createFirstRow("菜单信息");
                MenuExcleUtil.createSheetValue(menus);
                MenuExcleUtil.export(outputStream);

                return null;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    response.getWriter().print("<script>alert('导出失败!系统繁忙，请稍后重试!');window.history.back();</script>");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }else if (method.equals("deleteAll")){

            try {
                List<Integer> list = menuService.checkMenuInMiddleDelete(menuId);
                if (list.size()>0){
                    //查询正在使用的菜单的名称
                    List<Menu> menus = menuService.doExcle(list);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (Menu menu : menus) {
                        String menuNam=menu.getMenuName()+"、";
                        stringBuilder.append(menuNam);
                    }
                    response.getWriter().print("<script>alert('"+stringBuilder.toString()+"菜单正在使用中，没权限删除!');window.history.back();</script>");
                }else {

                    menuService.deleteAll(menuId);
                    response.getWriter().print("<script>alert('菜单已删除!');window.history.back();</script>");
                    String s = menuList(model, page, menuName);
                    return s;
                }
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    response.getWriter().print("<script>alert('菜单删除失败!系统繁忙，请稍后重试!');window.history.back();</script>");
                    String s = menuList(model, page, menuName);
                    return s;
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }

        }
        return null;
    }


    //查看菜单信息
    @RequestMapping("/resource/system/menu/menuLook")
    public String menuLook(Model model,@RequestParam("menuId") Integer menuId){

        Menu oldMenu = menuService.findMyMenuById(menuId);
        model.addAttribute("oldMenu",oldMenu);

        return "resource/system/menu/look";
    }
}
